import 'dart:async';

import 'package:flutter/material.dart';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';
import 'package:whale/helper/utils/util.dart';

class ImagePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) async {
    final recorder = ui.PictureRecorder();
    ui.Paint paint = Paint()
      ..isAntiAlias = true
      ..filterQuality = ui.FilterQuality.high;
    // 创建图像对象
    var image = await _loadUiImage('avater.png'.imgPathMe);

    // 获取图像的宽度和高度
    var imageWidth = image.width.toDouble();
    var imageHeight = image.height.toDouble();

    // 计算绘制矩形的位置和大小
    var x = (size.width - imageWidth) / 2;
    var y = (size.height - imageHeight) / 2;
    var width = imageWidth;
    var height = imageHeight;

    // 在画布上绘制矩形区域并填充图像
    canvas.drawImageRect(
      image,
      Rect.fromLTWH(x, y, width, height),
      Rect.fromLTWH(x, y, width / 2, height / 2),
      paint,
    );

    // 转换成图片
    final picture = recorder.endRecording();

    ui.Image img = await picture.toImage(width.toInt(), height.toInt());

    print('img的尺寸: $img');
    ByteData? _data = await img.toByteData(format: ui.ImageByteFormat.png);
    var _icondata = _data?.buffer.asUint8List();
  }

  Future<ui.Image> _loadUiImage(String imageAssetPath) async {
    final ByteData data = await rootBundle.load(imageAssetPath);
    final Completer<ui.Image> completer = Completer();
    ui.decodeImageFromList(Uint8List.view(data.buffer), (ui.Image img) {
      return completer.complete(img);
    });
    return completer.future;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // 如果图像发生更改，则重新绘制画布
    return oldDelegate != this;
  }
}
